package com.wenjh.jdmzt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.wenjh.jdmzt.service.model.User;
import com.wenjh.jdmzt.util.Log4Android;
import com.wenjh.jdmzt.util.StringUtils;
import com.wenjh.jdmzt.R;

public class AndroidKit {

	private static final String SDCARD_PATH_FORMAT = "Android/data/%s";

	private static Context applicationContext = null;
	private static ContentResolver sContentResolver = null;
	private static String sPackageName = null;
	private static Float sScreenDensity = null;
	private static Float sTextScale = null;
	private static File sExternalStorageDirectory = null;
	private static LayoutInflater layoutInflater = null;
	private static Log4Android log = new Log4Android("Momokit");

	public static void onApplicationCreate(Context context) {
		if (applicationContext == null) {
			applicationContext = context.getApplicationContext();
		}
	}

	/**
	 * 是否是4.0或者以后的系统
	 *
	 * @return
	 */
	public static boolean isIcsVsersion() {
		return Build.VERSION.SDK_INT >= 14;
	}

	public static void onApplicationTerminate() {
		applicationContext = null;
		sContentResolver = null;
		sPackageName = null;
		sScreenDensity = null;
		sTextScale = null;
		sExternalStorageDirectory = null;
	}

	public static Context getContext() {
		return applicationContext;
	}

	public static MApplication getApp() {
		return (MApplication) getContext().getApplicationContext();
	}

	public static User getCurrentUser() {
		return getApp().currentUser;
	}
	
	public static String getToken() {
		return getApp().token;
	}
	
	public static ContentResolver getContentResolver() {
		if (sContentResolver == null) {
			sContentResolver = applicationContext.getContentResolver();
		}
		return sContentResolver;
	}

	private static Animation avatorInAnimation = null;

	public static Animation getAvatorInAnimation() {
		if (avatorInAnimation == null) {
			avatorInAnimation = AnimationUtils.loadAnimation(getContext(),
					android.R.anim.fade_in);
			avatorInAnimation.setDuration(500);
		}
		return avatorInAnimation;
	}

	private static Animation avatorOutAnimation = null;

	public static Animation getAvatorOutAnimation() {
		if (avatorOutAnimation == null) {
			avatorOutAnimation = AnimationUtils.loadAnimation(getContext(),
					android.R.anim.fade_out);
			avatorOutAnimation.setDuration(500);
		}
		return avatorOutAnimation;
	}

	public static String getMarketSource() {
		try {
			ApplicationInfo ai = applicationContext.getPackageManager()
					.getApplicationInfo(getPackageName(),
							PackageManager.GET_META_DATA);
			Bundle bundle = ai.metaData;
			String source = bundle.getString("source");
			return source == null ? "" : source;
		} catch (Exception e) {
		}

		return "";
	}

	public static Activity getParentActivity(Activity activity) {
		Activity parent = activity.getParent();
		if (parent == null) {
			return activity;
		} else {
			return getParentActivity(parent);
		}
	}

	public static String getPackageName() {
		if (sPackageName == null) {
			sPackageName = applicationContext.getPackageName();
			if (sPackageName.indexOf(":") >= 0) {
				sPackageName = sPackageName.substring(0,
						sPackageName.lastIndexOf(":"));
			}
		}

		return sPackageName;
	}

	public static AudioManager getAudioManager() {
		return (AudioManager) applicationContext
				.getSystemService(Context.AUDIO_SERVICE);
	}

	public static float getScreenDensity() {
		if (sScreenDensity == null) {
			sScreenDensity = getDisplayMetrics().density;
		}
		return sScreenDensity.floatValue();
	}

	public static float getTextScale() {
		if (sTextScale == null) {
			sTextScale = getDisplayMetrics().scaledDensity;
		}
		return sTextScale.floatValue();
	}

	public static File getExternalStorageDirectory() {
		if (sExternalStorageDirectory == null) {
			sExternalStorageDirectory = new File(
					Environment.getExternalStorageDirectory(), String.format(
							Locale.US, SDCARD_PATH_FORMAT, getPackageName()));
		}
		return sExternalStorageDirectory;
	}

	public static Resources getResources() {
		return applicationContext.getResources();
	}

	public static Animation loadAnimation(int resId) {
		return AnimationUtils.loadAnimation(applicationContext, resId);
	}

	public static DisplayMetrics getDisplayMetrics() {
		return getResources().getDisplayMetrics();
	}

	public static SharedPreferences getSharedPreferences() {
		return PreferenceManager
				.getDefaultSharedPreferences(applicationContext);
	}

	public static String getString(int resource) {
		return applicationContext.getString(resource);
	}

	public static String getString(int resource, Object... formatArgs) {
		return applicationContext.getString(resource, formatArgs);
	}

	public static int getResourceId(String name) {
		return getResources().getIdentifier(name, null,
				applicationContext.getPackageName());
	}

	public static Drawable getDrawable(int resource) {
		return getResources().getDrawable(resource);
	}

	public static int getColor(int resource) {
		return getResources().getColor(resource);
	}

	public static Bitmap getBitmap(int resource) {
		return BitmapFactory.decodeResource(getResources(), resource);
	}

	public static int getPixels(float dip) {
		return Math.round(TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, dip, getDisplayMetrics()));
	}

	public static void registerReceiver(BroadcastReceiver receiver,
			IntentFilter filter) {
		applicationContext.registerReceiver(receiver, filter);
	}

	public static boolean tryUnregisterReceiver(BroadcastReceiver receiver) {
		try {
			applicationContext.unregisterReceiver(receiver);
			return true;
		} catch (Throwable t) {
			return false;
		}
	}

	public static Object getSystemService(String name) {
		return applicationContext.getSystemService(name);
	}

	/*
	 * wjh 修改 -- 将判断代码注释掉
	 */
	public static boolean isHoneycomb() {
		// Can use static final constants like HONEYCOMB, declared in later
		// versions
		// of the OS since they are inlined at compile time. This is guaranteed
		// behavior.
		return false /* Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB */;
	}

	/*
	 * wjh 修改 -- 将判断代码注释掉
	 */
	public static boolean isHoneycombTablet() {
		// Can use static final constants like HONEYCOMB, declared in later
		// versions
		// of the OS since they are inlined at compile time. This is guaranteed
		// behavior.
		return false;
		/*
		 * isHoneycomb() && (getResources().getConfiguration().screenLayout &
		 * Configuration.SCREENLAYOUT_SIZE_MASK) ==
		 * Configuration.SCREENLAYOUT_SIZE_XLARGE;
		 */

	}

	public static boolean getBoolPreference(String key, boolean defValue) {
		return getSharedPreferences().getBoolean(key, defValue);
	}

	public static int getIntPreference(String key, int defValue) {
		return getSharedPreferences().getInt(key, defValue);
	}

	public static float getFloatPreference(String key, float defValue) {
		return getSharedPreferences().getFloat(key, defValue);
	}

	public static long getLongPreference(String key, long defValue) {
		return getSharedPreferences().getLong(key, defValue);
	}

	public static String getStringPreference(String key, String defValue) {
		return getSharedPreferences().getString(key, defValue);
	}

	public static void setPreference(String key, boolean value) {
		SharedPreferences.Editor edit = getSharedPreferences().edit();
		edit.putBoolean(key, value);
		edit.commit();
	}

	public static void setPreference(String key, int value) {
		SharedPreferences.Editor edit = getSharedPreferences().edit();
		edit.putInt(key, value);
		edit.commit();
	}

	public static void setPreference(String key, float value) {
		SharedPreferences.Editor edit = getSharedPreferences().edit();
		edit.putFloat(key, value);
		edit.commit();
	}

	public static void setPreference(String key, long value) {
		SharedPreferences.Editor edit = getSharedPreferences().edit();
		edit.putLong(key, value);
		edit.commit();
	}

	public static void setPreference(String key, String value) {
		SharedPreferences.Editor edit = getSharedPreferences().edit();
		edit.putString(key, value);
		edit.commit();
	}

	/**
	 * wjh修改 添加方法
	 */
	public static LayoutInflater getLayoutInflater() {
		if (layoutInflater == null)
			layoutInflater = LayoutInflater.from(applicationContext);
		return layoutInflater;
	}

	/**
	 * wjh修改 添加方法
	 */
	public static boolean isFroyo() {
		if (Build.VERSION.SDK_INT >= 8) {
			return true;
		}
		return false;
	}


	public static Bitmap decodeBitmap(int resId) {
		return BitmapFactory.decodeResource(getResources(), resId);
	}
	
	

	/** 获取网络状态是否可用 ***/
	public static boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) applicationContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/** 获得应用程序版本 */
	public static int getVersionCode() {
		int versionCode = 0;
		try {
			PackageInfo pinfo = getContext().getPackageManager()
					.getPackageInfo(getPackageName(),
							PackageManager.GET_CONFIGURATIONS);
			versionCode = pinfo.versionCode;
		} catch (Exception e) {
			log.e(e);
		}
		return versionCode;
	}

	public static String getVersionName() {
		try {
			PackageInfo pinfo = getContext().getPackageManager()
					.getPackageInfo(getContext().getPackageName(),
							PackageManager.GET_CONFIGURATIONS);
			return pinfo.versionName;
		} catch (Exception e) {
			log.e(e);
		}
		return "";
	}

	/** 获得SDK版本号 */
	public static int getSDKVersion() {
		return Build.VERSION.SDK_INT;
	}

	/** 获得手机操作系统版本号 */
	public static String getOSVersion() {
		return Build.VERSION.RELEASE;
	}

	/** 获得手机IMEI号 */
	public static String getIMEI() {
		TelephonyManager telephonyManager = (TelephonyManager) applicationContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getDeviceId();
	}

	/** 获得手机网卡地址 */
	public static String getMAC() {
		WifiManager wifi = (WifiManager) applicationContext
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();

	}

	/** 获得手机型号 */
	public static String getModle() {
		return Build.MODEL;

	}

	/** 获得手机固件编译版本 */
	public static String getFirmwareVersion() {
		// htc_asia_wwe/htc_pyramid/pyramid:2.3.3/GRI40/84734:user/release-keys
		String version = Build.FINGERPRINT;
		int index = version.lastIndexOf(":");
		if (index > 0) {
			String subString = version.substring(0, index);
			String[] strs = subString.split("/");
			if (strs.length > 2) {
				version = "";
				version += strs[strs.length - 2] + "/";
				version += strs[strs.length - 1];
			}
		}
		return version;

	}


	/** 获取屏幕分辨率宽度 **/
	public static int getScreenWidth() {
		return getDisplayMetrics().widthPixels;
	}

	/** 获取屏幕分辨率高度 **/
	public static int getScreenHeight() {
		return getDisplayMetrics().heightPixels;
	}

	/** 获取当前系统的国家代号字符串 **/
	public static String getSystemCountry() {
		return Locale.getDefault().getCountry();
	}

	/** 获取当前系统的语言代号字符串 **/
	public static String getSystemLanguage() {
		return Locale.getDefault().getLanguage();
	}

	/**
	 * 获得移动运营商名称
	 *
	 * @return
	 */
	public static String getSimOperatorName() {
		TelephonyManager tm = (TelephonyManager) applicationContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (tm != null) {
			return tm.getNetworkOperatorName();
		}
		return "UNKNOW";
	}

	public static String getRadioDetail() {
		TelephonyManager tm = (TelephonyManager) applicationContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getNetworkType() + "";

	}

	/**
	 * 解析图片文件，返回图片对象。根据设备自动调整图片大小
	 *
	 * @param file
	 * @return
	 */
	public static Bitmap decodeResourceBitmap(File file, int resid) {
		if (!file.exists()) {
			return null;
		}
		try {
			return decodeResourceBitmap(new FileInputStream(file), resid);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	public static Bitmap decodeResourceBitmap(InputStream is, int resId) {
		try {
			Rect pad = new Rect();
			BitmapFactory.Options opts = new BitmapFactory.Options();
			try {
				Method method = DisplayMetrics.class
						.getDeclaredMethod("getDeviceDensity");
				method.setAccessible(true);
				opts.inScreenDensity = (Integer) method
						.invoke(DisplayMetrics.class);
			} catch (Exception e) {
				log.e(e);
			}

			TypedValue value = new TypedValue();
			Resources resources = getResources();
			resources.getValue(resId, value, false);

			final int density = value.density;
			if (density == TypedValue.DENSITY_DEFAULT) {
				opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
			} else if (density != TypedValue.DENSITY_NONE) {
				opts.inDensity = density;
			}
			opts.inTargetDensity = resources.getDisplayMetrics().densityDpi;

			Bitmap bitmap = BitmapFactory.decodeStream(is, pad, opts);
			is.close();

			return bitmap;
		} catch (Exception e) {
		}

		return null;
	}

	public static String getIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					String ip = inetAddress.getHostAddress();
					String[] splits = ip.split("\\.");
					if (!inetAddress.isLoopbackAddress()) {
						try {
							Integer.parseInt(splits[0]);
							return ip;
						} catch (Exception e) {
						}
					}
				}
			}
		} catch (Exception e) {
		}

		return "";
	}

	/**
	 * 获得指定apk文件的签名信息
	 * @param apkPath
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Signature getApkSignature(String apkPath) throws Exception {
		Class clazz = Class.forName("android.content.pm.PackageParser");
		Method method = clazz.getMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class);
		
		Object packageParser = clazz.getConstructor(String.class).newInstance("");
		Object packag = method.invoke(packageParser, new File(apkPath), null, getContext().getResources().getDisplayMetrics(), 0x0004);
		
		method = clazz.getMethod("collectCertificates", Class.forName("android.content.pm.PackageParser$Package"), int.class);
		method.invoke(packageParser, packag, PackageManager.GET_SIGNATURES);
		
		Signature mSignatures[] = (Signature[]) packag.getClass().getField("mSignatures").get(packag);
		return mSignatures.length > 0 ? mSignatures[0] : null;
	}
	
	/**
	 * 获得当前程序的apk的签名信息
	 * @return
	 * @throws Exception
	 */
	public static Signature getApkSignature() throws Exception {
		return getApkSignature(getContext().getApplicationInfo().publicSourceDir);
	}
	
	/**
	 * 获得指定apk的签名指纹（md5）
	 * @return
	 * @throws Exception
	 */
	public static String getApkSignatureString(String path) throws Exception {
		Signature apkSignature = getApkSignature(path);
		if(apkSignature != null) {
			return StringUtils.md5(apkSignature.toCharsString());
		}
		return null;
	}
	
	/**
	 * 获得当前程序的apk的签名指纹（md5）
	 * @return
	 * @throws Exception
	 */
	public static String getApkSignatureString() throws Exception {
		Signature apkSignature = getApkSignature();
		if(apkSignature != null) {
			return StringUtils.md5(apkSignature.toCharsString());
		}
		return null;
	}

	/** wifi网络 **/
	public static final String NETWORK_TYPE_WIFI = "wifi";
	/** 手机网络 **/
	public static final String NETWORK_TYPE_MOBILE = "mobile";

	/** 获取当前网络类型 **/
	public static String getNetWorkType() {
		ConnectivityManager connManager = (ConnectivityManager) applicationContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();// 获取网络的连接情况
		if (activeNetInfo != null) {
			if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				return NETWORK_TYPE_WIFI;
			} else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				return NETWORK_TYPE_MOBILE;
			}
		}
		return null;
	}
	
	/**
	 * @see ConnectivityManager#TYPE_MOBILE
	 * @see ConnectivityManager#TYPE_WIFI
	 * 
	 * @return
	 */
	public static int getNetType() {
		try {
			ConnectivityManager connManager = (ConnectivityManager) applicationContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
			if (activeNetInfo != null) {
				return activeNetInfo.getType();
			}
		} catch (Exception e) {
		}
		return -1;
	}
	
	/**
	 * @see TelephonyManager#NETWORK_TYPE_CDMA
	 * @see TelephonyManager#NETWORK_TYPE_EDGE
	 * @see TelephonyManager#NETWORK_TYPE_GPRS
	 * @return
	 */
	public static int getMobileNetType() {
		try {
			TelephonyManager manager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
			return manager.getNetworkType();
		} catch (Exception e) {
		}
		return -1;
	}
	
	/** 当前是WIFI网络，而不是移动网络**/
	public static boolean isWifi() {
		return NETWORK_TYPE_WIFI.equals(getNetWorkType());
	}
	
	/** 当前是移动网络，而不是WIFI网络**/
	public static boolean isMobile() {
		return NETWORK_TYPE_MOBILE.equals(getNetWorkType());
	}

	/**
	 * 检测是否为cmwap网络模式
	 *
	 * @return
	 */
	public static boolean isCMWAP() {
		String currentAPN = "";
		ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		currentAPN = info.getExtraInfo();
		if (currentAPN == null || currentAPN == "") {
			return false;
		} else {
			if (currentAPN.toLowerCase().equals("cmwap")) {
				return true;
			} else {
				return false;
			}

		}
	}
	
	public static boolean isWifiOpen() {
		WifiManager mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
		int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
		if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/***
	 * 按照指定的字节数截取字符串(GBK)
	 * @param str 要截取的字符串
	 * @param subSLength 要截取的字节数
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String subStr(String str, int subSLength)    
            throws UnsupportedEncodingException{   
        if (str == null)    
            return "";    
        else{   
            int tempSubLength = subSLength;//截取字节数  
            String subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);//截取的子串    
            int subStrByetsL = subStr.getBytes("GBK").length;//截取子串的字节长度   
            //int subStrByetsL = subStr.getBytes().length;//截取子串的字节长度   
            // 说明截取的字符串中包含有汉字    
            while (subStrByetsL > tempSubLength){    
                int subSLengthTemp = --subSLength;  
                subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);    
                subStrByetsL = subStr.getBytes("GBK").length;  
                //subStrByetsL = subStr.getBytes().length;  
            }    
            return subStr;   
        }  
    } 

	private static final Map<String, Object> cacheMap = new HashMap<String, Object>();

	public static void saveCache(String key, Object cache) {
		cacheMap.put(key, cache);
	}

	public static Object getCache(String key) {
		return cacheMap.get(key);
	}
	
	public static void clearCache() {
		cacheMap.clear();
	}
	
	private static boolean isHeadset = false;
	/** 获取当前是否为耳机插入状态 */
	public static boolean isHeadset(){
		return isHeadset;
	}
	
	/**设置当前是否为耳机插入状态 */
	public static void setHeadset(boolean isheadset){
		isHeadset = isheadset;
	}

}
